import requests
import json
import sys

url = "https://api.minimaxi.com/v1/image_generation"
api_key="Your-api-Key"
def generate_image(prompt):
    payload = json.dumps({
    "model": "image-01", 
    "prompt": f"{prompt}，根据这个地点生成一张风景图片，红色中国风剪纸风格",
    "aspect_ratio": "16:9",
    "response_format": "url",
    "n": 3,
    "prompt_optimizer": True
    })
    headers = {
    'Authorization': f'Bearer {api_key}',
    'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    print(response.json())
    return response

def down_load(url):
    """
    从给定的 URL 下载文件并保存到本地。
    """
    filename = 'generate_image.jpg'
    print(f"准备从URL下载图片: {url}")
    
    try:
        # 使用 requests.get 发起网络请求，stream=True 用于流式下载
        response = requests.get(url, stream=True, timeout=10) # 增加超时设置
        
        # 检查请求是否成功，如果不成功（状态码 4xx 或 5xx），会抛出 HTTPError 异常
        response.raise_for_status()
        
        # 以二进制写入模式(wb)打开文件
        print(f"请求成功，准备写入文件: {filename}")
        with open(filename, "wb") as f:
            # response.iter_content(chunk_size=8192) 是更推荐的写法
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)
                
        print(f"图片已成功下载到: {filename}")

    except requests.exceptions.RequestException as e:
        # 捕获所有 requests 可能抛出的网络相关异常
        print(f"下载失败，网络请求错误: {e}", file=sys.stderr)
        
    except IOError as e:
        # 捕获文件写入错误，例如权限不足
        print(f"下载失败，文件写入错误: {e}", file=sys.stderr)

def text_to_img(text):
    # response = generate_image(text)
    # down_load(response.json()['data']['image_urls'][0])
    down_load('https://hailuo-image-algeng-data.oss-cn-wulanchabu.aliyuncs.com/image_inference_output%2Ftalkie%2Fprod%2Fimg%2F2025-07-06%2Fbbe71f01-1cf6-439c-aa57-2faa72490ebf.jpeg?Expires=1751871053&OSSAccessKeyId=LTAI5t5i98DA24TibFGGcX8h&Signature=Z18bqt0bvp7hcl69z8Tp9SB12h4%3D')
    
if __name__ == '__main__':
    response = generate_image("敦煌")
    print(response)
    down_load(response.json()['data']['image_urls'][0])
    # down_load('https://hailuo-image-algeng-data.oss-cn-wulanchabu.aliyuncs.com/image_inference_output%2Ftalkie%2Fprod%2Fimg%2F2025-07-06%2F50b9bc98-b349-4eef-985d-91693b67b7ec.jpeg?Expires=1751823130&OSSAccessKeyId=LTAI5t5i98DA24TibFGGcX8h&Signature=essWFyjnWG%2FNDtsRiId5b%2FPmB8g%3D')
